﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bee.Web;
using System.Timers;
using System.Web;
using Bee.Net;
using Bee.Net.WebSocket;
using System.Threading;

namespace Bee.Admin
{
    public class WebSocketManager
    {
        private static WebSocketManager instance = new WebSocketManager();

        private List<ISocketConnection> allSockets = new List<ISocketConnection>();
        private object m_SessionSyncRoot = new object();

        private WebSocketServer server = null;

        private WebSocketManager()
        {
        }

        public static WebSocketManager Instance
        {
            get
            {
                return instance;
            }
        }

        public void Start(int port)
        {
            server = new WebSocketServer(port, string.Format("ws://localhost:{0}", port));
            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Open!");
                            allSockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Close!");
                            allSockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine(message);

                            Thread.Sleep(1000);
                            allSockets.ToList().ForEach(s => s.Send(System.Threading.Thread.CurrentThread.ManagedThreadId+"Echo: " + message));
                        };
                });
        }

        public void Stop()
        {
            allSockets.ForEach(s => s.Close());
            if (server != null)
            {
                server.Stop();
            }
        }

        public void SendToAll(string message)
        {
            //lock (m_SessionSyncRoot)
            {
                foreach (var s in allSockets)
                {
                    s.Send(message);
                }
            }
        }
    }
}
